import { makeDiv } from "../core/utils/utils";
import GoodModules from "../game/goods/get_good";
import { getDayTime } from "../game/time";

export default {
  addGood(isCreate = false){
    if(!this.mapClip || !(this.mapSite || isCreate)){
      this.dialogs.showWarning('警告', '未选中可选的地区放置固有Good');
      return;
    }

    let data = {
      key: false,
      storeId: this.storeId++,
      goodAttr: {
        worldPos: this.mapClip.worldPos,
        mapPos: null
      }
    };

    if(isCreate){
      data.goodAttr.isSave = false;
      data.goodAttr.mapPos = [];
      data.generate = true;
      data.generateMax = 1;
      data.recoveryDayTime = 0;
    } else {
      data.goodAttr.mapPos = this.mapSite.mapPos;
    }

    this.mapData.goods.push(data)

    this.renderAllGoods();
  },

  editGood(good, isCreate = false){
    let btns = ['key:success:Key:unclose', 'attr:success:属性:unclose', 'remove:bad:删除', 'cancel:bad:取消'];

    if(isCreate){
      btns = ['pos:success:定位', 'num:success:数量:unclose', 'day:success:时间:unclose'].concat(btns);
    }

    let goodDialog = this.dialogs.showInfo('编辑Good', '对此Good进行属性操作', 
      btns
    );

    goodDialog.key.add(() => {
      let { optionSelected } = this.dialogs.showOptionChooser('选择Good', {
        active: good.key,
        options: Object.keys(GoodModules).map(key => ({
          value: key,
          text: key,
          desc: ''
        }))
      })

      optionSelected.add(val => {
        good.key = val;

        this.renderAllGoods();
      })
    })

    goodDialog.attr.add(() => {
      let multipleDialog = this.dialogs.showMultipleItem('编辑属性', {
        items: Object.keys(good.goodAttr.data || {}).map(key => ({
          key, val: good.goodAttr.data[key]
        })),
        confirmDialog: (item) => {
          return new Promise(resolve => {
            let { confirm } = this.dialogs.showInput('属性', [
              {
                text: 'Key',
                key: 'key',
                value: item ? item.key : ''
              },
              {
                text: 'Value',
                key: 'val',
                value: item ? item.val : ''
              },
            ])

            confirm.add((inputValue) => {
              resolve(inputValue)
            })
          })
        }
      })

      multipleDialog.removed.add(data => {
        let attr = {};
        data.forEach(item => {
          attr[item.key] = item.val;
        });
        good.goodAttr.data = attr;

        this.renderAllGoods();
        this.dialogs.showInfo('删除成功', `成功将good中指定属性删除`);
      })

      multipleDialog.confirm.add((data, item) => {
        if(item){
          let obj = {};
          Object.keys(good.goodAttr.data || {}).map(key => {
            if(key == item.key) obj[data.key] = data.val;
            else obj[key] = good.goodAttr.data[key];
          })
          good.goodAttr.data = obj;
        } else {
          if(!good.goodAttr.data) good.goodAttr.data = {};
          good.goodAttr.data[data.key] = data.val;
        }
        this.renderAllGoods();
      })
    })

    goodDialog.remove.add(() => {
      let { ok } = this.dialogs.showWarning('警告', '你正在进行删除Good操作',
        ['cancel:bad:取消', 'ok:success:确认']  
      );

      ok.add(() => {
        this.mapData.goods = this.mapData.goods.filter(item => {
          if(item.storeId != good.storeId) return true;
        })
        this.renderAllGoods();
      })
    })

    if(isCreate){
      goodDialog.pos.add(() => {
        this.htmlElement.querySelector('.tip').innerHTML = '已进入长编辑模式';
        this.useMultipleEditMode(() => {
          good.goodAttr.mapPos = this.activeMaps.map(item => item.split(','));
          // this.dialogs.showInfo('定位数据', this.activeMaps.join('、'));
          this.renderMapClipGoods();
        }, good.goodAttr.mapPos.map(item => item.join(',')))
      })

      goodDialog.num.add(() => {
        let { confirm } = this.dialogs.showInput('上限数量', [
          {
            text: '数量',
            key: 'num',
            value: good.generateMax
          },
        ])

        confirm.add(data => {
          good.generateMax = data.num;
          this.renderMapClipGoods();
        })
      })

      goodDialog.day.add(() => {
        let { confirm } = this.dialogs.showInput('生成时间间隔', [
          {
            text: '时间(day)',
            key: 'day',
            value: good.recoveryDayTime
          }
        ])

        confirm.add(data => {
          good.recoveryDayTime = data.day;
          this.renderMapClipGoods();
        })
      })
    }
  },

  renderMapSiteGoods(){
    if(!this.mapSite){
      return;
    }

    let goods = this.getPosGoods(this.mapClip.worldPos, this.mapSite.mapPos);
    let goodsParent = this.htmlElement.querySelector('.good-page .mapSiteGoods');
    goodsParent.innerHTML = '';

    if(goods.length > 0){
      goods.map(item => {
        let attrText = '';
        Object.keys(item.goodAttr.data || {}).map(key => {
          attrText += `<p>${key}: ${item.goodAttr.data[key]}</p>`
        })

        let dom = makeDiv(goodsParent, '', ['styledButton', 'success', 'mb-1'], `
          <p>ID: ${item.storeId}</p>
          <p>Key: ${item.key}</p>
          <h5>自定义属性</h5>
          ${attrText || '<p>无设置</p>'}
        `);

        this.trackClicks(dom, () => {
          this.editGood(item);
        })
      })
    } else {
      goodsParent.innerHTML = '<p>此地没有任何Good</p>'
    }
  },

  renderMapClipGoods(){
    let goods = this.getGenerateGoods(this.mapClip.worldPos);
    let goodsParent = this.htmlElement.querySelector('.create-good-page .mapSiteGoods');
    goodsParent.innerHTML = '';

    if(goods.length > 0){
      goods.map(item => {
        let attrText = '';
        Object.keys(item.goodAttr.data || {}).map(key => {
          attrText += `<p>${key}: ${item.goodAttr.data[key]}</p>`
        })
        let createText = `${item.recoveryDayTime}天(游戏时间) / ${(getDayTime() * item.recoveryDayTime) / 1000}s(现实时间)`;
  
        let dom = makeDiv(goodsParent, '', ['styledButton', 'success', 'mb-1'], `
          <p>ID: ${item.storeId}</p>
          <p>Key: ${item.key}</p>
          <p>上限数量: ${item.generateMax}</p>
          <p>刷新时间: ${item.recoveryDayTime <= 0 ? '仅生成一次' : createText}</p>
          <p>放置区域: ${item.goodAttr.mapPos.map(item => item.join(',')).join('、')}</p>
          <h5>自定义属性</h5>
          ${attrText || '<p>无设置</p>'}
        `);

        this.trackClicks(dom, () => {
          this.editGood(item, true);
        })
      })
    } else {
      goodsParent.innerHTML = '<p>此地没有固有good</p>';
    }
  },

  renderAllGoods(){
    this.renderMapSiteGoods();
    this.renderMapClipGoods();
  }
}